import { ERROR, LOADED, LOADING } from "./types"
import { loadImg } from "@/utils"

export class Img {
    constructor({
        el,
        src,
        err,
        loading,
        preload,
        render
    }) {
        this.el = el
        this.src = src
        this.err = err
        this.loading = loading
        this.preload = preload
        this.render = render
        this.loaded = false
    }

    get visible() {
        const { top, left, width, height } = this.el.getBoundingClientRect(),
            { clientHeight, clientWidth } = document.documentElement

        return (
            top < clientHeight * (this.preload || 1.1) &&
            top > -height &&
            left < clientWidth * (this.preload || 1.1) &&
            left > -width
        )
    }

    load() {
        this.render(LOADING)

        return new Promise((resolve, reject) => {
            loadImg(this.src)
                .then(() => {
                    this.render(LOADED).then(() => {
                        this.loaded = true
                        resolve()
                    })
                })
                .catch(() => {
                    this.render(ERROR).then(() => {
                        this.loaded = true
                        reject()
                    })
                })
        })
    }
}